# Flask框架导入
from flask import Blueprint, render_template, redirect, url_for, flash

# 工具函数导入
from .utils import (
    member_login_required,
    get_current_member,
    get_accessible_menus,
    format_date_filter,
    status_text_filter,
    status_class_filter
)

# 服务层函数导入
from .jira.services import get_jira_projects
from .approval.services import get_pending_approval_count

# 子蓝图导入
from .auth import auth_bp
from .userinfo import userinfo_bp
from .jira import jira_bp
from .task import task_bp
from .approval import approval_bp

from inc.models import db, SystemConfig  # 移到顶部

# 创建主蓝图
member_bp = Blueprint('member', __name__)

# 注册子蓝图
member_bp.register_blueprint(auth_bp, url_prefix='/auth')
member_bp.register_blueprint(userinfo_bp, url_prefix='/userinfo')
member_bp.register_blueprint(jira_bp, url_prefix='/jira')
member_bp.register_blueprint(task_bp, url_prefix='/task')
member_bp.register_blueprint(approval_bp, url_prefix='/approval')

# 主路由定义
@member_bp.route('/')
@member_login_required
def index():
    """会员中心首页"""
    member = get_current_member()
    if not member:
        flash("会员信息未找到", "error")
        return redirect(url_for('member.login'))

    projects = get_jira_projects(member.id)
    pending_approval_count = get_pending_approval_count(member.id)
    system_config = SystemConfig.get_config()
    # 仅在新建时add，避免重复add
    if not db.session.object_session(system_config):
        db.session.add(system_config)

    return render_template('member/index.html',
                         member=member,
                         projects=projects,
                         pending_approval_count=pending_approval_count,
                         system_config=system_config)

@member_bp.route('/dashboard')
@member_login_required
def dashboard():
    """登录后仪表盘"""
    return render_template('member/dashboard.html')

@member_bp.route('/stats')
@member_login_required
def member_stats():
    """会员工作统计"""
    member = get_current_member()
    if not member:
        flash("会员信息未找到", "error")
        return redirect(url_for('member.login'))
    return render_template('member/stats.html', member=member)

# 添加上下文处理器
@member_bp.context_processor
def inject_pending_approval_count():
    """注入待审批任务数量到所有模板"""
    member = get_current_member()
    if member:
        return {'pending_approval_count': get_pending_approval_count(member.id)}
    return {}

# 注册模板过滤器
member_bp.add_app_template_filter(format_date_filter)
member_bp.add_app_template_filter(status_text_filter)
member_bp.add_app_template_filter(status_class_filter)